<template>
    <div class="account-box">
        <div class="toggle">
          <a @click="isMsgLogin=false" href="javascript:;" v-if="isMsgLogin">
              <i class="iconfont icon-yonghu1"></i> 使用账号登录
          </a>
          <a @click="isMsgLogin=true" href="javascript:;" v-else>
              <i class="iconfont icon-duanxin"></i> 使用短信登录
          </a>
        </div>

        <!-- 账户登录区域开始 -->
        <el-form :model="form" :rules="accRules" ref="accLoginForms" class="form" v-show="!isMsgLogin">
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" autocomplete="off" :prefix-icon="User"/>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input type="password" v-model="form.password" placeholder="请输入密码" autocomplete="off" :prefix-icon="Lock" show-password/>
          </el-form-item>

          <!-- 协议条款开始 -->
          <div class="agree" v-if="!isMsgLogin">
              <el-checkbox name="type" :checked="form.is_agree" @click="form.is_agree = !form.is_agree">
                <span>我已同意</span>
                <a href="javascript:;">《隐私条款》</a>
                <span>和</span>
                <a href="javascript:;">《服务条款》</a>
              </el-checkbox>
          </div>
          <div class="error" v-if="isAgreeMsg">{{ isAgreeMsg }}</div>
          <!-- 协议条款结束 -->

          <a @click="handlerAccLogin" href="javascript:;" class="btn">登录</a>
        </el-form>
        <!-- 账户登录区域结束 -->


        <!-- /////////////////////////////////////////////////////// -->


        <!-- 短信登录区域开始 -->
        <el-form :model="form" :rules="msgRules" ref="msgLoginForms" class="form" v-show="isMsgLogin">
          <!-- 手机号 -->
          <el-form-item prop="mobile">
            <el-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号" autocomplete="off" :prefix-icon="Iphone"/>
          </el-form-item>

          <!-- 验证码开始 -->
          <el-form-item prop="code">
            <el-input style="width: 188px;margin-right: 10px;" v-model="form.code" placeholder="请输入6为数字验证码" autocomplete="off" :prefix-icon="Lock" maxlength="6"/>
            <el-button 
                :disabled="!rightMobile"
                :color="!rightMobile ? 'gray' : '#27BA9B'"
                style="--el-button-text-color: #fff;--el-button-hover-text-color: #fff"
                @click="sendCode">
                {{time ? '剩余' + time + 's' : '发送验证码'}}
            </el-button>
          </el-form-item>
          

          <!-- 协议条款开始 -->
          <div class="agree" v-if="isMsgLogin">
              <el-checkbox name="type" :checked="form.is_agree" @click="form.is_agree = !form.is_agree">
                <span>我已同意</span>
                <a href="javascript:;">《隐私条款》</a>
                <span>和</span>
                <a href="javascript:;">《服务条款》</a>
              </el-checkbox>
          </div>
          <div class="error" v-if="isAgreeMsg">{{ isAgreeMsg }}</div>
          <!-- 协议条款结束 -->
          
          <a @click="handlerMsgLogin" href="javascript:;" class="btn">登录</a>
        </el-form>
        <!-- 账户登录区域结束 -->

        <div class="action">
          <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
            <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
          </a>
          <div class="url">
              <RouterLink to="/forgot-password">忘记密码</RouterLink>
              <RouterLink to="/register">免费注册</RouterLink>
          </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, watch, computed} from 'vue'
import { useUserStore } from "@/stores/modules/user"
import { useCartStore } from "@/stores/modules/cart"
import { useRouter, useRoute } from 'vue-router'

import { reqLoginSendCodeAPI } from "@/apis/user"

import { User, Lock, Iphone } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'


// ------------------- 定义全局变量开始 -------------------
// 定义用户存储
const userStore = useUserStore()

// 定义购物车存储
const cartStore = useCartStore()

// 定义路由器
const router = useRouter()

// 定义路由
const route = useRoute()

// 是否短信登录
const isMsgLogin = ref(false)
// 表单信息对象
const form = reactive({
    is_agree: false,
    username: '',
    password: '',
    mobile: '',
    code: ''
})

// 账户登录表单
const accLoginForms = ref()

// 短信登录表单
const msgLoginForms = ref()


// ------------------- 定义全局变量结束 -------------------


// 监控切换短信、账户登录
watch(isMsgLogin, () => {
  // 还原数据
  form.is_agree = false
  form.username = ''
  form.password = ''
  form.mobile = ''
  form.code = ''
  isAgreeMsg.value = ''
  // 移除该表单项的校验结果
  accLoginForms.value.clearValidate()
  msgLoginForms.value.clearValidate()
})



// ------------------ 发送验证码功能开始 ------------------
const rightMobile = computed(() => {
	// 手机正则
	const pattern = /^1[3|5|7|8|9]\d{9}$/
	return pattern.test(form.mobile)
})

// 过期时间
const time = ref(0)

// 发送验证码
const sendCode = async () => {
	if(time.value == 0) {
		// 请求验证码接口
		await reqLoginSendCodeAPI(form.mobile)
		
    ElNotification({
        type: 'success',
        message: '发送成功'
    });
		
		time.value = 60
		const intervalId = setInterval(() => {
			time.value--
			if(time.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}
// ------------------ 发送验证码功能结束 ------------------



// --------------------- 登录功能开始 ---------------------
//自定义校验规则函数
const validatorMobile = (rule, value, callback) => {
  
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  const pattern = /^1[3|5|7|8|9]\d{9}$/
  if (pattern.test(value)) {
    callback();
  } else {
    callback(new Error('请输入格式正确的手机号'));
  }
}

const validatorCode = (rule, value, callback) => {
    const pattern = /^[0-9]*[1-9][0-9]*$/
    if (pattern.test(value) && value.length == 6) {
        callback();
    } else {
        callback(new Error('请输入6为数字验证码'));
    }
}

// 定义短信表单校验需要配置对象
const msgRules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  mobile: [
    // { required: true, min: 6, max: 10, message: '账号长度至少六位', trigger: 'change' }
    { trigger: 'change', validator: validatorMobile }
  ],
  code: [
    // { required: true, min: 6, max: 15, message: '密码长度至少6位', trigger: 'change' }
    { trigger: 'change', validator: validatorCode }
  ]
}

// 定义账号表单校验需要配置对象
const accRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' }
  ]
}

const isAgreeMsg = ref('')

// 监控是否勾选协议
watch(() => form.is_agree, (oldValue, newValue) => {
  if (!newValue) {
    isAgreeMsg.value = ''
  }
})

// 处理账户登录
const handlerAccLogin = async () => {
  //保证全部表单相校验通过再发请求
  await accLoginForms.value.validate();
  if (!form.is_agree) {
    isAgreeMsg.value = '请勾选同意协议'
    return
  }
  await userStore.login(form)
  ElNotification({
    type: 'success',
    message: '欢迎回来'
  });

  // 获取购物车数据
  await cartStore.getCartList()

  setTimeout(() => {
    const redirectUrl = decodeURIComponent(route.query.redirect)
    
    // 登录成功后，跳转url不为空并且不等于退出页，则跳转至跳转url，否则跳转至首页
    // 必须跳转至我的页面的redirectUrl
    const unRedirectUrls = [
      '/login',
      '/register',
    ]

    if (redirectUrl == "undefined" || redirectUrl == "" || redirectUrl == 'null'|| unRedirectUrls.includes(redirectUrl)) {
      router.push({path: '/'})
    } else {
      const params = queryURLparams(redirectUrl)
      router.push({path: redirectUrl, query: params})
    }
  }, 1000)
}

// 处理短信登录
const handlerMsgLogin = async () => {
  //保证全部表单相校验通过再发请求
  await msgLoginForms.value.validate();
  if (!form.is_agree) {
    isAgreeMsg.value = '请勾选同意协议'
    return
  }

  await userStore.login(form, 2)
  ElNotification({
    type: 'success',
    message: '欢迎回来'
  });

  // 获取购物车数据
  await cartStore.getCartList()

  setTimeout(() => {
    const redirectUrl = decodeURIComponent(route.query.redirect)
    
    // 登录成功后，跳转url不为空并且不等于退出页，则跳转至跳转url，否则跳转至首页
    // 必须跳转至我的页面的redirectUrl
    const unRedirectUrls = [
      '/login',
      '/register',
    ]

    if (redirectUrl == "undefined" || redirectUrl == "" || redirectUrl == 'null'|| unRedirectUrls.includes(redirectUrl)) {
      router.push({path: '/'})
    } else {
      const params = queryURLparams(redirectUrl)
      router.push({path: redirectUrl, query: params})
    }
  }, 1000)
}


// 解下URL参数
const queryURLparams = (url) => {
    let obj = {}
    if (url.indexOf('?') < 0) return obj
    let arr = url.split('?')
    url = arr[1]
    let array = url.split('&')
    for (let i = 0; i < array.length; i++) {
        let arr2 = array[i]
        let arr3 = arr2.split('=')
        obj[arr3[0]] = arr3[1]
    }
    return obj
}
// --------------------- 登录功能结束 ---------------------
</script>

<style scoped lang="scss">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: $main-color;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: $price-color;
          }
          &.active,&:focus {
            border-color: $main-color;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $price-color;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .error {
      color: $error-color;
      padding-bottom: 5px;
      font-size: 12px;
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $main-color;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>